package com.wds;

import com.wds.common.utils.RedisCacheUtils;
import com.wds.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author WDs , wds8.24@outlook.com
 * @version 1.0
 * @since 2022-12-03 11:35
 */
@Component
@Slf4j
public class ViewCountJob {

    @Autowired
    private RedisCacheUtils redisCache;
    @Autowired
    private ArticleService articleService;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void testJob() {
        // 每隔多长时间，将redis中的浏览量存储到mysql
        Map<Long, Long> viewCountMap = redisCache.getCacheLongMap("viewCountMap");
        for (Map.Entry<Long, Long> viewCounts : viewCountMap.entrySet()) {
            Long id = viewCounts.getKey();
            Long viewCount = viewCounts.getValue();
            articleService.updateViewCountToMysql(id, viewCount);
        }
        log.info("浏览量序列化到Mysql完成,计数:{}", viewCountMap.size());
    }
}
